package com.cortex.carambola.view;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.VideoView;

import com.cortex.animation.CortexAnimatin;
import com.cortex.carambola.fetch.FetchImages;
import com.cortex.carambola.fetch.FetchImages.OnStateChanged;
import com.cortex.carambola.fetch.FetchVideos;
import com.cortex.carambola.fetch.FetchVideos.Video;
import com.cortex.carambola.listener.DragDropView;
import com.cortex.carambola.summary.CarambolaSummary;
import com.cortex.carambola.view.CortexHorizontalScrollView.OnScrollChangedListener;
import com.cortex.carambolasummary.R;



public class SummarySavedView extends RelativeLayout{

	private TextView tvName,tvSummary;
	private ImageView imgShowMoreSummary;
	private View vGoToUrl,vSideline;
	private TextView tvCharactersNumber;
	private LinearLayout llGallaryMedia;
	private ProgressBar pbWaitMedia;
	private Spinner snFilterGalleryMedia;
	private CortexHorizontalScrollView hsvGalleryMedia;
	private CarambolaSummary summary;
	private boolean isShowMoreSummary = false;
	private Browser browser;
	private FetchImages fetchImages;
	private FetchVideos fetchVideos;
	private ShowMedia showMedia;
	private DragDropView dragDropView;


	public SummarySavedView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public SummarySavedView(Context context) {
		super(context);
	}
	@Override
	protected void onFinishInflate() {
		// TODO Auto-generated method stub
		super.onFinishInflate();
		init();
	}

	private void init(){
		tvName = (TextView)findViewById(R.id.tvSummaryName);
		tvSummary = (TextView)findViewById(R.id.tvSummary);
		imgShowMoreSummary = (ImageView)findViewById(R.id.imgShowMoreSummary);
		tvCharactersNumber = (TextView)findViewById(R.id.tvCharactersNumber);
		llGallaryMedia = (LinearLayout)findViewById(R.id.containerMedia);
		pbWaitMedia = (ProgressBar)findViewById(R.id.pbWaitImages);
		hsvGalleryMedia = (CortexHorizontalScrollView)findViewById(R.id.hsvGalleryMedia);
		vGoToUrl = (View)findViewById(R.id.tvGoToUrl);
		(((TextView)((ViewGroup)vGoToUrl).findViewById(R.id.tvLink))).setText(getResources().getString(R.string.goToUrl));
		vSideline = (View)findViewById(R.id.sideline);

		snFilterGalleryMedia = (Spinner)findViewById(R.id.snFilter);
		List<String> list = new ArrayList<String>();
		// get all filter of gallery from resources
		String[] items = getResources().getStringArray(R.array.filters_gallery_arrays);
		for (int i = 0; i < items.length; i++) {
			list.add(items[i]);
		}
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getContext(),
				android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		snFilterGalleryMedia.setAdapter(dataAdapter);
		// to allow copy of text
		tvSummary.setTextIsSelectable(true);
		fetchImages = new FetchImages();
		fetchVideos = new FetchVideos();
		initHandlers();
		initView();
	}
	private void initView(){
		changeHeightSize(getContext().getResources().getDimensionPixelSize(R.dimen.summary_saved_normal_height));
	}
	private void initHandlers(){
		imgShowMoreSummary.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				changeShowMoreSummary();
			}
		});
		vGoToUrl.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				browser.loadUrl(summary.getUrl());
			}
		});
		hsvGalleryMedia.setOnScrollChangedListener(new OnScrollChangedListener() {

			@Override
			public void scrollChanged(int l, int t, int oldl, int oldt) {

				// We take the last son in the scrollview
				View view = (View) hsvGalleryMedia.getChildAt(hsvGalleryMedia.getChildCount() - 1);
				int diff = (view.getRight() - (hsvGalleryMedia.getWidth() + hsvGalleryMedia.getScrollX()));

				// if diff is zero, then the right has been reached
				if (diff == 0) {
					// start fetching 5 images and videos from url of summary 
					startFetchMedia();
				}
			}
		});
		fetchImages.setOnStateChanged(new OnStateChanged() {

			@Override
			public void timeLoadStarted() {
				waitToMedia(true);
			}

			@Override
			public void timeLoadFinished(List<Bitmap> images) {
				waitToMedia(false);
			}

			@Override
			public void timeLoadCanceled(String message) {
				waitToMedia(false);
			}

			@Override
			public void downloadedData(final Bitmap image, int downloadNumber, int amount) {
				post(new Runnable() {

					@Override
					public void run() {
						Drawable drawable = new BitmapDrawable(getResources(), image);
						addImageToGallery(drawable);
					}
				});
			}
		});
		vSideline.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					if(dragDropView != null){
						dragDropView.start();
					}
				}
				return false;
			}
		});
		fetchVideos.setOnStateChanged(new com.cortex.carambola.fetch.FetchVideos.OnStateChanged() {

			@Override
			public void timeLoadStarted() {
				waitToMedia(true);
			}

			@Override
			public void timeLoadFinished(List<Video> videosUrl) {
				for (Video video : videosUrl) {
					addVideoToGallery(video);
				}
				waitToMedia(false);
			}

			@Override
			public void timeLoadCanceled(String message) {
				waitToMedia(false);
			}

			@Override
			public void downloadedData(Video url, int downloadNumber, int amount) {
				// TODO Auto-generated method stub

			}
		});
		snFilterGalleryMedia.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> adapter, View view,
					int position, long id) {
				for (int i = 0; i < llGallaryMedia.getChildCount(); i++) {
					View child = llGallaryMedia.getChildAt(i);
					if(!(child instanceof ProgressBar)){
						child.setVisibility(VISIBLE);
					}
					switch(position){
					case 0:// no filter
						child.setVisibility(VISIBLE);
						break;
					case 1:// only pictures
						if(!(child instanceof ImageView)){
							child.setVisibility(GONE);
						}
						break;
					case 2:// only videos
						if(!(child instanceof VideoView)){
							child.setVisibility(GONE);
						}
						break;
					default:
						break;

					}

				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
	}
	private void waitToMedia(boolean isWait){
		if(isWait && !pbWaitMedia.isShown()){
			pbWaitMedia.setVisibility(View.VISIBLE);
		}
		else{
			if(!fetchImages.isRunning() && !fetchVideos.isFetching()){
				pbWaitMedia.setVisibility(View.GONE);
			}
		}
	}
	public void setBrowser(Browser browser){
		this.browser = browser;
	}
	public String getUrl(){
		return summary.getUrl();
	}
	public CarambolaSummary getSummary() {
		return summary;
	}
	public void setSummary(CarambolaSummary summary) {
		this.summary = summary;
	}
	public void show(){
		tvName.setText(summary.getName());
		tvSummary.setText(summary.getSummary());
		tvCharactersNumber.setText("" + summary.getCharacters());
		startFetchMedia();
	}
	private void startFetchMedia(){
		fetchImages.startFetching(summary.getUrl(), 5);
		fetchVideos.startFetching(summary.getUrl(),5);
	}
	private void changeShowMoreSummary(){
		// change size of summary
		isShowMoreSummary = !isShowMoreSummary;
		int height;
		Animation animation;
		if(isShowMoreSummary){
			height = LayoutParams.WRAP_CONTENT;
			animation = CortexAnimatin.loadAnimation(getContext(), R.anim.rotate_45_to_right);
			setVisibleMoreInfo(VISIBLE);
			vSideline.setVisibility(GONE);
		}
		else{
			height = getContext().getResources().getDimensionPixelSize(R.dimen.summary_saved_normal_height);
			animation = CortexAnimatin.loadAnimation(getContext(), R.anim.rotate_45_to_left);
			setVisibleMoreInfo(GONE);
			vSideline.setVisibility(VISIBLE);
		}
		changeHeightSize(height);
		imgShowMoreSummary.startAnimation(animation);
	}
	private void setVisibleMoreInfo(int visible){
		vGoToUrl.setVisibility(visible);
		snFilterGalleryMedia.setVisibility(visible);
		((View) tvCharactersNumber.getParent()).setVisibility(visible);
	}
	private void changeHeightSize(int height){
		LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvSummary.getLayoutParams();
		params.height = height;
		tvSummary.setLayoutParams(params);
	}
	public void setShowMedia(ShowMedia showMedia){
		this.showMedia = showMedia;
	}
	public void setDragDrop(DragDropView dragDropView){
		this.dragDropView = dragDropView;
	}
	public boolean isShowMoreSummary() {
		return isShowMoreSummary;
	}
	public void setShowMoreSummary(boolean isShowMoreSummary) {
		changeShowMoreSummary();
	}
	private void addVideoToGallery(final Video video){
		VideoView videoView = new VideoView(getContext());
		videoView.setBackgroundResource(R.drawable.back_on);
		videoView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_UP){
					if(showMedia != null){
						showMedia.showVideo(video);
					}
				}
				return true;
			}
		});
		addViewToGallery(videoView,160,100);
		summary.addVideo(video);
	}



	private void addImageToGallery(Drawable drawable){
		ImageView image = new ImageView(getContext());
		image.setBackgroundDrawable(drawable);
		addViewToGallery(image,drawable.getMinimumWidth(),drawable.getMinimumHeight());
		summary.addImage(drawable);
	}
	private void addViewToGallery(View v,int pxWidth,int pxHeight){
		int pxMaxWidth = 160;
		int pxMaxHeight = 100;
		if(pxWidth > pxMaxWidth){
			pxWidth = pxMaxWidth;
		}
		if(pxHeight > pxMaxHeight){
			pxHeight = pxMaxHeight;
		}
		int positionImage = llGallaryMedia.getChildCount()-1;
		llGallaryMedia.addView(v,positionImage);

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pxWidth, pxHeight);
		int margin = 5;
		params.rightMargin = margin;
		params.leftMargin = margin;
		params.topMargin = margin;
		params.bottomMargin = margin;
		v.setLayoutParams(params);
		v.setFocusable(false);
	}
}
